package TCPEchoServerAndSlient0407;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.SimpleTimeZone;

/**
 * Description:
 * User:岁亮亮
 * Date:2025-04-07
 * TIME:20:50
 */
public class TcpEchoServerDemo {

    //建立一个文件描述符表
    private ServerSocket serverSocket;

    public TcpEchoServerDemo(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            Socket socket = serverSocket.accept();
            System.out.printf("客户端 [%s] 上线",socket.getInetAddress());
            correspond(socket);
        }
    }

    private void correspond(Socket socket) throws IOException {
        Scanner scanner = new Scanner(socket.getInputStream());
        PrintWriter writer = new PrintWriter(socket.getOutputStream());
        while(true){
            //等待客户端请求的到来 接收请求
            //TCP面向字节流来进行传输 不需要如DatagramPacket数据报类进行再封装一层
            if(!scanner.hasNext()){
                System.out.printf("客户端下线 [%s]",socket.getInetAddress());
                break;
            }
            //这里规定 客户端发来的请求以空格符 结尾 来表示一个应用层数据报 解决粘包问题
            String request = scanner.next();
            //根据请求构造响应
            String response = process(request);
            //发送响应
            //这里规定 服务器发送的响应
            writer.println(response);
            writer.flush();

            //打印日志
            System.out.printf("[ %s : %d ]  req : %s  resp : %s",socket.getInetAddress(),socket.getPort()
                                                                  ,request,response);
        }


    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServerDemo tcpEchoServerDemo = new TcpEchoServerDemo(9090);
        tcpEchoServerDemo.start();
    }


}
